package org.wattdepot.cli.command;

import java.util.ArrayList;
import java.util.List;
import org.wattdepot.cli.CommandLineInterface;
import org.wattdepot.client.BadXmlException;
import org.wattdepot.client.MiscClientException;
import org.wattdepot.client.NotAuthorizedException;
import org.wattdepot.client.ResourceNotFoundException;
import org.wattdepot.resource.property.jaxb.Properties;
import org.wattdepot.resource.source.jaxb.Source;

/**
 * Returns a table of fuels associated with this source.
 * 
 * @author Anthony Xu & John Mack
 *
 */
public class FueltypesCommand implements WattDepotCliCommand {
  
  /**
   * Returns a table of fuels associated with this source.
   * 
   * @param cli WattDepotClient with hostUri = http://server.wattdepot.org:8182/wattdepot/
   * @param commands user's command line input
   * @return string to output
   */
  public String doCommand(CommandLineInterface cli, List<String> commands) {
    String str = "";
    ArrayList<Source> sourceList = new ArrayList<Source>();
    try {
      Source source = cli.getClient().getSource(commands.get(1));
      sourceList.add(source);
      int sourceCount = 0;
      while (sourceCount < sourceList.size()) {
        if (sourceList.get(sourceCount).isVirtual()) {
          List<String> children = source.getSubSources().getHref();
          for (int i = 0; i < children.size(); i++) {
            String url = children.get(i);
            String sourceName = url.substring(url.lastIndexOf('/') + 1);
            Source subsource = cli.getClient().getSource(sourceName);
            sourceList.add(subsource);
          }
          sourceList.remove(sourceCount);
        }
        else {
          sourceCount++;
        }
      }
      StringBuffer buffer = new StringBuffer();
      for (int j = 0; j < sourceList.size(); j++) {
        Properties property = sourceList.get(j).getProperties();
        String sourceProperty = property.toString();
        int start = sourceProperty.lastIndexOf("value") + 6;
        String fuel = sourceProperty.substring(start, sourceProperty.length() - 2);
        buffer.append(fuel + " : " + sourceList.get(j).getName() + "\n");
      }
      str += buffer.toString();
    }
    catch (NotAuthorizedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    catch (ResourceNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    catch (BadXmlException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    catch (MiscClientException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return str;
  }

}
